﻿using System.Security;
using System.Windows.Forms;
using System.Security.Permissions;
using System;

namespace ManagedSandbox
{
    public partial class UIPermissionForm : Form, IPermissionEditor
    {
        public IPermission Permission { get; private set; }

        public UIPermissionForm()
        {
            InitializeComponent();
        }

        public void Initialize(IPermission permission)
        {
            Permission = permission;

            var uiPermission = Permission as UIPermission;

            foreach (var item in Enum.GetValues(typeof(UIPermissionWindow)))
            {
                permissionWindowComboBox.Items.Add(item);
            }

            permissionWindowComboBox.SelectedIndex = 0;

            foreach (var item in Enum.GetValues(typeof(UIPermissionClipboard)))
            {
                permissionClipBoardComboBox.Items.Add(item);
            }

            permissionClipBoardComboBox.SelectedIndex = 0;

            if (null != uiPermission)
            {
                if (uiPermission.IsUnrestricted())
                {
                    unrestrictedCheckBox.Checked = true;
                    permissionPanel.Enabled = false;
                }
                else
                {
                    permissionWindowComboBox.SelectedItem = uiPermission.Window;
                    permissionClipBoardComboBox.SelectedItem = uiPermission.Clipboard;
                }
            }
        }

        public CheckState GetCheckState()
        {
            var uiPermission = Permission as UIPermission;

            if (null == uiPermission)
                return CheckState.Unchecked;

            if (uiPermission.IsUnrestricted())
                return CheckState.Checked;

            return (UIPermissionWindow.NoWindows == uiPermission.Window &&
                    UIPermissionClipboard.NoClipboard == uiPermission.Clipboard)
                       ? CheckState.Unchecked
                       : CheckState.Indeterminate;
        }

        private void unrestrictedCheckBoxCheckedChanged(object sender, EventArgs e)
        {
            permissionPanel.Enabled = !unrestrictedCheckBox.Checked;
        }

        private void okButtonClick(object sender, EventArgs e)
        {
            if (unrestrictedCheckBox.Checked)
                Permission = new UIPermission(PermissionState.Unrestricted);
            else
                Permission = new UIPermission(
                    (UIPermissionWindow)permissionWindowComboBox.SelectedItem,
                    (UIPermissionClipboard)permissionClipBoardComboBox.SelectedItem);

            DialogResult = DialogResult.OK;
        }
    }
}
